package interview.xunlei.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileScanner {
	String rootName ="";
	List fileList = new ArrayList();

	public FileScanner(String directName,String regx) {
		rootName=directName;
		getDir(directName,regx);
	}

	private void getDir(String directName,String regx) {

		try {
			File f = new File(directName);
			String tempName = null;
			if (f.isDirectory()) {
				File[] fList = f.listFiles();
				for (int j = 0; j < fList.length; j++) {
					if (fList[j].isDirectory()) {
						getDir(fList[j].getPath(),regx);
					}
					tempName = fList[j].getName();
					if (tempName.contains(".")) {
						if (tempName.substring(tempName.indexOf("."))
								.equalsIgnoreCase(".java")
								&& ReadFile(fList[j].getPath(),regx)) {
							tempName=fList[j].getAbsolutePath();
							tempName=tempName.replace("\\", "/");
							tempName=tempName.replace(rootName, "");
							tempName = tempName.substring(0, tempName
									.indexOf("."));
							tempName=tempName.replace("/", ".");
							fileList.add(tempName);
						}
					}
				}
			}
		} catch (Exception e) {
			System.out.println("Error： " + e);
		}
	}

	public boolean ReadFile(String fileName,String regx) {
		
		
		try {
			FileReader in = new FileReader(fileName);
			BufferedReader bin = new BufferedReader(in, 512);
			char[] bytes = new char[512];
			int count = 0;
			while ((count = bin.read(bytes, 0, bytes.length)) != -1) {
				String temp = new String(bytes,0,count);
				Pattern pattern = Pattern.compile(regx);
				Matcher matcher = pattern.matcher(temp);
				if (matcher.find()) {
					return true;
				}
			}
			bin.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static void main(String[] args) {
		// getDir("d:\\12345");

		FileScanner fs = new FileScanner("d:/12345/",".*\\s+implements\\s+IMethod\\s+.*");
		List fileList = fs.fileList;
		for (Iterator iter = fileList.iterator(); iter.hasNext();) {
			String ele = (String) iter.next();
			System.out.println(ele);
		}

//		Pattern pattern = Pattern.compile(".*\\s+implements\\s+IMethod\\s+.*");
//		//Pattern pattern = Pattern.compile(".*");
//		Matcher matcher = pattern.matcher("fds  implements \n\t  IMethod   fds");
//		boolean b = matcher.find();
//		//当条件满足时，将返回true，否则返回false
//		System.out.println(b);
		 
		
		//System.out.println(ReadFile("d:\\12345\\EqualMethod.java"));;

	}

	public List getFileList() {
		return fileList;
	}

}